<?php


namespace App\Http\Controllers\User\userCenter;


use App\Http\Controllers\Controller;
use App\Services\MemberService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 兑换控制器
 * Class DhController
 * @package App\Http\Controllers\User\userCenter
 */
class DhController extends Controller
{
    /**
     * 游戏
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGames()
    {
        $gameName = request()->get('key');
        $where = [];
        if ($gameName) {
            $where[] = ['server_name', 'like', "%{$gameName}%"];
        }
        $list = DB::table('game_data')
            ->select(['id', 'server_name'])
            ->where($where)
            ->orderBy('id', 'desc')
            ->limit(20)
            ->get();
        return successResp($list);
    }

    /**
     * 服务器列表
     * @param $gameId
     * @return \Illuminate\Http\JsonResponse
     */
    public function getServerList($gameId)
    {
        $list = DB::table('game_server')
            ->select(['id', 'server_name'])
            ->where('game_id', $gameId)
            ->get();
        return successResp($list);
    }

    /**
     * 提交兑换
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function commitDh(Request $request)
    {
        //验证表单
        $this->validate($request, [
            'game_id' => ['required','int'],
            'game_server_id' => ['required','int'],
            'game_account' => ['required','string'],
            'money' => ['required','int'],
            'balance_type' => ['required','int'], // 1乐游币  2玩服积分
        ]);
        if ($request->money <= 0) {
            return errorResp('请输入兑换金额');
        }
        $dhBalance = DB::table('sys_config')->where('key', 'dh_balance')->value('value');
        if ($dhBalance) {
            $dhBalance = json_decode($dhBalance, true);
            if (!in_array((int)$request->money, $dhBalance)) {
                return errorResp('兑换金额错误');
            }
        }
        $game = DB::table('game_data')->find($request->game_id);
        if (!$game) {
            return errorResp('游戏错误');
        }
        $server = DB::table('game_server')->find($request->game_server_id);
        if (!$server || $server->game_id != $game->id) {
            return errorResp('区服错误');
        }
        $sourceUrl  = $_SERVER['HTTP_HOST'];
        $user = $request->userInfo;
        $balance = $user->ly_balance;
        $balanceField = MemberService::BalanceTypeLy;
        $balanceName = '乐游币';
        if ($request->balance_type == 2) {
            $balance = $user->wf_integral;
            $balanceField = MemberService::BalanceTypeWf;
            $balanceName = '玩服积分';
        }
        // 扣用户余额
        if ($balance < $request->money) {
            return errorResp('余额不足');
        }
        DB::beginTransaction();
        try {

            $res = DB::table('draw_log')->insertGetId([
                'user_id' => $user->id,
                'is_luck' => 1,
                'money' => $request->money,
                'create_time' => date('Y-m-d H:i:s'),
                'game_num' => $request->game_account,
                'game_url' => $game->server_name,
                'game_server' => $server->server_name,
                'status' => 2,
                'date' => '今日',
                'draw_id' => 0,
                'game_id' => $game->id,
                'balance_type' => $request->balance_type,
                'source_url' => $sourceUrl,
            ]);
            if (!$res) {
                throw new \Exception('获取信息写入失败');
            }
            MemberService::setMemberBalance(
                $user,
                $balanceField,
                MemberService::FromTypeDh,
                $res,
                -$request->money,
                "兑换【{$game->server_name}】{$request->money}{$balanceName}"
            );
            if ($request->balance_type == 1) {
                // 乐游币兑换写入游戏充值表
                $order = [
                    'pay_plat_id' => 0,
                    'user_id' => $user->id,
                    'unionid' => $user->unionid,
                    'money' => ($request->money)/100,
                    'req_params' => '{}',
                    'pay_type' => 'WEIXIN',
                    'order_no' => date('YmdHis').$user->id.$res,
                    'pay_status' => 1,
                    'game_account' => $request->game_account,
                    'game_version' => $this->game_info['game_version'] ?? '',
                    'game_server' => $game->server_name,
                    'game_role' => '',
                    'create_time' => time(),
                    'update_time' => time(),
                    'site_host' => $_SERVER['HTTP_HOST'] ?? '',
                    'order_type' => 2,
                    'plat_order_no' => '',
                    'contact' => '',
                ];
                $orderId = DB::table('game_recharge_order')->insertGetId($order);
                if (!$orderId) {
                    throw new \Exception('生成订单失败');
                }
            }
            DB::commit();
            return successResp('');
        } catch (\Exception $e) {
            DB::rollBack();
            return errorResp($e->getMessage());
        }
    }

    /**
     * 获取兑换记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getDhLog(Request $request)
    {
        $user = $request->userInfo;
        $list = DB::table('draw_log')
            ->where('user_id', $user->id)
            ->where('draw_id', 0)
            ->orderBy('id', 'desc')
            ->limit(30)
            ->get();
        return successResp($list);
    }

    public function getGameById(Request $request)
    {
        $data = [];
        if ($request->get('id')) {
            $data = DB::table('game_data')
                ->select(['id', 'server_name'])
                ->find($request->get('id'));
        }
        return successResp($data);
    }
}
